package tpenchere.service;

import java.io.InputStream;
import java.util.Properties;

import org.apache.log4j.Logger;
import org.omg.CORBA.ORB;
import org.omg.CORBA.StringHolder;
import org.omg.CosNaming.NamingContextExt;
import org.omg.CosNaming.NamingContextExtHelper;

import tpenchere.model.Categorie;
import tpenchere.model.Enchere;
import tpenchere.model.Produit;

public class Client {
	static String SERVICE_NAME = EnchereService.class.getName();
	static String GLASS = "glassfishorb.properties";
	static String JACORB = "jacorb.properties";
	static String SUN = "sunorb.properties";
	static String IUP = "iuporb.properties";

	private static Logger log = Logger.getLogger(Client.class);
	private static Client instance = null;
	static EnchereServiceOperations serviceImpl;

	public static void main(String args[]) {
		new Client().getService();
		serviceImpl.getAllProduct();
		log.info("getAllProduct");
		Produit p = serviceImpl.createProduit(new Produit(0, SUN, SUN, SUN,
				new Categorie(0, GLASS, new Categorie[0]), 0, 0, 0));
		log.info("createProduit");
		log.info(p.idProduit);
		p = serviceImpl.createProduit(new Produit(0, GLASS, SUN, SUN,
				new Categorie(0, GLASS, new Categorie[0]), 0, 0, 0));
		log.info("createProduit");
		log.info(p.idProduit);
	}

	private Client() {
		String orbPropertyFile = IUP;
		try {

			// create and initialize the ORB
			log.info("loading orb.properties: " + orbPropertyFile);

			InputStream is = getClass().getResourceAsStream(
					"/" + orbPropertyFile);
			log.info("input stream: " + is);
			Properties props = new Properties();
			props.load(is);

			// create and initialize the ORB
			ORB orb = ORB.init(new String[0], props);

			// get the root naming context
			org.omg.CORBA.Object objRef = orb
					.resolve_initial_references("NameService");
			// Use NamingContextExt instead of NamingContext. This is
			// part of the Interoperable naming Service.
			NamingContextExt ncRef = NamingContextExtHelper.narrow(objRef);

			// resolve the Object Reference in Naming

			serviceImpl = EnchereServiceHelper.narrow(ncRef
					.resolve_str(SERVICE_NAME));

			log.info("Obtained a handle on server object");

		} catch (Exception e) {
			System.out.println("ERROR : " + e);
			e.printStackTrace(System.out);
		} finally {
			if (serviceImpl != null && !orbPropertyFile.equals(IUP)) {
				serviceImpl.shutdown();
			}

		}
	}

	public static Client getInstance() {
		if (instance == null) {
			instance = new Client();
		}
		return instance;
	}

	public EnchereServiceOperations getService() {
		return serviceImpl;
	}

}
